<?php
/**
 * 将数据格式化成树形结构
 * @author 王建
 * @param array $items
 * @return array
 */
if(!function_exists("genTree9")){
	function genTree9($items,$id = 'id' ,$pid = 'pid' ,$child = 'children' ) {
		$tree = array(); //格式化好的树
		foreach ($items as $item)
			if (isset($items[$item[$pid]]))
			$items[$item[$pid]][$child][] = &$items[$item[$id]];
		else
			$tree[] = &$items[$item[$id]];
		return $tree;
	}
}
if(!function_exists("tree_format")){
	function tree_format(&$list,$pid=0,$level=0,$html='--',$pid_string = 'pid' ,$id_string = 'id'){
		static $tree = array();
		foreach($list as $v){
			if($v[$pid_string] == $pid){
				$v['sort'] = $level;
				$v['html'] = str_repeat($html,$level);
				$tree[] = $v;
				tree_format($list,$v[$id_string],$level+1,$html);
			}
		}
		return $tree;
	}
}


/**
 * 格式化select
 * @author 王建
 * @param array $parent
 * @deep int 层级关系
 * @return array
 */
if(!function_exists("getChildren")){
	function getChildren($parent,$deep=0) {
		foreach($parent as $row) {
			$data[] = array("id"=>$row['id'], "name"=>$row['name'],"pid"=>$row['pid'],'deep'=>$deep,'url'=>$row['url']);
			if (isset($row['childs']) && !empty($row['childs'])) {
				$data = array_merge($data, getChildren($row['childs'], $deep+1));
			}
		}
		return $data;
	}
}

//获得MySql的版本号
if(!function_exists("getversion")){
	function getversion($isformat=true)
	{
		$res = M()->query("SELECT VERSION()  as a");
		$mysql_version = $res[0]['a'];
		if($isformat)
		{
			$mysql_versions = explode(".",trim($mysql_version));
			$mysql_version = number_format($mysql_versions[0].".".$mysql_versions[1],2);
		}
		return $mysql_version;
	}	
}

/*
 * 后台输出的json数据
* author 王建
* time 2014_01_20
*
*/

if( !function_exists("result_to_towf_new") ){

	function result_to_towf_new($vDataResult, $ret,$errmsg,$sigInfo){
		$result_arr = array();
		$result_arr["resultcode"] = (string)$ret;
		$tmp_arr["errmsg"] = $errmsg;
		$tmp_arr["obj"] = $sigInfo;
		$vResult = array();
		$tmp_arr["list"] = $vDataResult;
		$result_arr["resultinfo"] = $tmp_arr;

		return json_encode($result_arr);
	}

}

/*
 *@记录系统操作日志文件到数据库里面
**sql 是要插入数据库中的 log_sql的值
*$action 动作
*$person 操作人
*$ip ip地址
*status 操作是否成功 1成功 0失败
*message 失败信息
*groupname_ 定义数据库连接信息的时候的 groupname
*/
if(!function_exists("write_action_log") ){
	function write_action_log($sql,$url = '' ,$person = '' ,$ip = '',$status = '1' ,$message = '' , $groupname_ = "real_data"){
		if(!C('is_write_log_to_database')){//是否记录日志文件到数据表中
			return false ;
		}
		$time = date("Y-m-d H:i:s",time());
		$time_table = date("Ym",time());
		$table_pre = C("DB_PREFIX") ;

		$sql_table = <<<EOT
CREATE TABLE IF NOT EXISTS `{$table_pre}admin_log_{$time_table}` (
  `log_id` mediumint(8) NOT NULL auto_increment,
  `log_url` varchar(50) NOT NULL,
  `log_person` varchar(16) NOT NULL,
  `log_time` datetime NOT NULL,
  `log_ip` char(15) NOT NULL,
  `log_sql` text NOT NULL,
  `log_status` tinyint(1) NOT NULL default '1',
  `log_message` text NOT NULL,
  PRIMARY KEY  (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
EOT;
		
		M()->query($sql_table);
		$insert_data = array(
				'log_url'=>$url ,
				'log_person'=>$person ,
				'log_time'=>$time ,
				'log_ip'=>$ip ,
				'log_sql'=>$sql ,
				'log_status'=>$status ,
				'log_message'=>$message
		) ;
		M("admin_log_{$time_table}")->add($insert_data) ;
	}
}
/*
 *遍历数组 ， 并且去掉每个值后面的/
*@params $array
*@return array
*/
if(!function_exists("delete_str_")){
	function delete_str_($array = array() ){
		$data = array();
		if(is_array($array) && $array){
			foreach($array as $kk => $vv ){
				//$url = isset($array[$i])?$array[$i]:'' ;
	
				if(substr($vv,-1) == '/'){
					$vv= substr($vv,0,-1) ;
				}
				if($vv != '' ){
					$data[] = $vv ;
				}
			}
		}
		return $data ;
	}
}

//获取模块名和操作名称组成的字符串
if(!function_exists("getModuleAction")){
	function getModuleAction(){
		$url = (parse_url(__SELF__));
		$url = $url['query'] ;
		parse_str($url);
		$model = C("VAR_MODULE") ;
		$action = C("VAR_ACTION");
		return $$model."/".$$action ;
		//return $_REQUEST[C("VAR_URL_PARAMS")][1]."/".$_REQUEST[C("VAR_URL_PARAMS")][2] ;
		//return strtolower(MODULE_NAME)."/".strtolower(ACTION_NAME) ;
	}
}

/**
 * 获取后台登陆的数据
 * @author 王建
 * @param $string 解密的值
 * @return array
 */
if(!function_exists("decode_data")){
	function decode_data($string = '' ){
		$data = array() ;
		$encode_string = '' ;
		$encode_string = ($string != "" )?$string:C('admin_auth') ;

		//$encode_string = isset($_COOKIE['admin_auth'])?$_COOKIE['admin_auth']:'' ;
		if(empty($encode_string)){
			return $data ;
		}
		$encode_string = auth_code($encode_string,"DECODE",C("s_key"));
		$data = unserialize($encode_string) ;
		return $data ;
	}
}
/**
 * 获取字段名称,返回,号的字符串
 * @author 王建
 * @param $field ,号分割的字符串
 * @param $must_field //必填的字段 数组形式
 * @param $default_field //默认字段名称   数组形式
 * @param $all_field //所有的字段名称 包括了 上面2个 数组形式
 * @return array
 */
if(!function_exists("getField")){
	function getField($must_field , $default_field ,$all_field , $field = '' ){
		$fieldString = '' ;
		if(!$field){//如果没有 ， 显示默认的字段
			$fieldArray = array_flip(array_merge($must_field , $default_field ));
			$fieldString = implode("," , $fieldArray);
		}else{
			$fieldArray = explode(",",$field) ;
			$fieldData = array_merge($must_field , $all_field  );
	
			foreach($fieldArray as $kk => $vv){
				if(array_key_exists($vv, $fieldData)){
					$fieldString.=$vv.",";
				}
			}
			$fieldString = rtrim($fieldString , ',') ;
	
			if(empty($fieldString)){
				$fieldString = implode(",", array_flip(array_merge($must_field , $default_field )));
			}else{
				$re = explode("," , $fieldString);
				$fieldString = implode("," ,array_merge(array_keys($must_field) ,$re) ) ;
			}
			$fieldArray = explode("," , $fieldString);
			$fieldArray = array_unique($fieldArray) ;
			$fieldString = implode(",",$fieldArray);
		}
		$fieldString = sort_by_allField($fieldString , $all_field) ;
		return array('field' => $fieldString);
	}
}
/**
 * 处理排序 ，按照all_field 的数组下标进行排序
 * @author 王建
 * @param $fieldString ,号分割的字符串
 * @param $all_field //所有的字段名称  数组形式
 * @return array
 */
if(!function_exists("sort_by_allField")){
	function sort_by_allField($fieldString , $all_field){
		$field = '' ;
		$fieldData = explode(",", $fieldString) ;
		foreach($all_field as $all=>$val){
			if(in_array($all , $fieldData)){
				$field.=$all.",";
			}
		}
		$field = rtrim($field , ',') ;
		return $field ;
	}
}

/**
 * //根据字段获取表格的头部
 * @author 王建
 * @param $fieldString ,号分割的字符串
 * @param $must_field //必填的字段 数组形式
 * @param $default_field //默认字段名称   数组形式
 * @param $all_field //所有的字段名称 包括了 上面2个 数组形式
 * @return array
 */
if(!function_exists("getHead")){
	function getHead($fieldString = '',$must_field , $default_field ,$all_field ){
		if(!$fieldString){
			return array() ;
		}
		$result = array();
		$all = array_merge($must_field , $default_field , $all_field);
		$re = explode("," , $fieldString);
		foreach($re as $k => $v ){
			if(array_key_exists($v, $all)){
				$result[$v] = $all[$v];
			}
		}
		return $result ;
	}
}

